package com._101aiot.auth.service.impl;

import cn.hutool.json.JSONUtil;
import com._101aiot.auth.api.AuthToken;
import com._101aiot.auth.exception.ExceptionCast;
import com._101aiot.auth.service.AuthService;
import com._101aiot.common.resultutil.ResultCode;
import com._101aiot.redis.core.RedisService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 登录 退出 存redis
 *
 * @author Administrator
 * @version 1.0
 **/
@Slf4j
@Service
@AllArgsConstructor
public class AuthServiceImpl implements AuthService {

    /**
     * 构造器注入 RedisService
     */
    private final RedisService redisService;

    private final RestTemplate restTemplate;

    private final LoadBalancerClient loadBalancerClient;


    @Override
    public AuthToken login(String username, String password, String clientId, String clientSecret) {

        // 请求spring security申请令牌
        AuthToken authToken = this.applyToken(username, password, clientId, clientSecret);

        // 令牌申请失败
        if (authToken == null) {

            ExceptionCast.cast(ResultCode.AUTH_LOGIN_APPLY_TOKEN_FAIL);
        }
        // 用户身份令牌
        String accessToken = authToken.getAccessToken();

        // 反序列化 存储到redis中的内容
        String jsonString = JSONUtil.toJsonStr(authToken);

        // 将令牌存储到redis
        boolean result = this.saveToken(accessToken, jsonString, 1200);
        if (!result) {

            ExceptionCast.cast(ResultCode.AUTH_LOGIN_TOKEN_SAVE_FAIL);
        }
        return authToken;

    }

    /**
     * 申请令牌
     *
     * @param username     用户名称
     * @param password     密码
     * @param clientId     客户端ID
     * @param clientSecret 客户端加密密码
     * @return AuthToken 对象
     */
    private AuthToken applyToken(String username, String password, String clientId, String clientSecret){
        //从eureka中获取认证服务的地址（因为spring security在认证服务中）
        //从eureka中获取认证服务的一个实例的地址
        ServiceInstance serviceInstance = loadBalancerClient.choose("app-auth");
        //此地址就是http://ip:port
        URI uri = serviceInstance.getUri();
        //令牌申请的地址 http://localhost:40400/auth/oauth/token
        String authUrl = uri+ "/oauth/token";
        //定义header
        LinkedMultiValueMap<String, String> header = new LinkedMultiValueMap<>();
        String httpBasic = getHttpBasic(clientId, clientSecret);
        header.add("Authorization", httpBasic);

        //定义body
        LinkedMultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("grant_type","password");
        body.add("username",username);
        body.add("password",password);

        // 客户端
//        body.add("client_id","myApp");
//        body.add("client_secret","myApp");

        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(body, header);
        //String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables


        // TODO 这边处理远程调用的各种提示

        //设置restTemplate远程调用时候，对400和401不让报错，正确返回数据
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                if(response.getRawStatusCode()!=400 && response.getRawStatusCode()!=401){
                    super.handleError(response);
                }
            }
        });

        ResponseEntity<Map> exchange = restTemplate.exchange(authUrl, HttpMethod.POST, httpEntity, Map.class);

        //申请令牌信息
        Map bodyMap = exchange.getBody();
        if(bodyMap == null ||
                bodyMap.get("access_token") == null ||
                bodyMap.get("refresh_token") == null ||
                bodyMap.get("jti") == null){

            //解析spring security返回的错误信息
            if(bodyMap!=null && bodyMap.get("error_description")!=null){
                String error_description = (String) bodyMap.get("error_description");
                // 抛出此信息 账号不存在
                if(error_description.contains("UserDetailsService returned null")){
                    ExceptionCast.cast(ResultCode.AUTH_ACCOUNT_NOT_EXISTS);
                }else if(error_description.contains("用户名或密码错误")){
                    // 密码错误， 账号或密码错误
                    ExceptionCast.cast(ResultCode.AUTH_CREDENTIAL_ERROR);
                }
            }

            return null;
        }

        AuthToken authToken = new AuthToken();
        authToken.setAccessToken((String) bodyMap.get("jti"));//用户身份令牌
        authToken.setRefreshToken((String) bodyMap.get("refresh_token"));//刷新令牌
        authToken.setJwtToken((String) bodyMap.get("access_token"));//jwt令牌
        return authToken;
    }

    /**
     * 存储到令牌到redis 并立即判断有效时间
     *
     * @param access_token 用户身份令牌
     * @param content      内容就是AuthToken对象的内容
     * @param ttl          过期时间
     * @return boolean
     */
    private boolean saveToken(String access_token, String content, long ttl) {

        String key = "user_token:" + access_token;
        // 存入redis
        redisService.setStr(key, content, ttl, TimeUnit.SECONDS);

        // 查询存入成功否
        Long expire = redisService.getExpire(key);
        return expire > 0;
    }


    /**
     * 获取http basic的串
     *
     * @param clientId     clientId
     * @param clientSecret clientSecret
     * @return String
     */
    private String getHttpBasic(String clientId, String clientSecret) {
        String string = clientId + ":" + clientSecret;
        // 将串进行base64编码
        byte[] encode = Base64Utils.encode(string.getBytes());
        return "Basic " + new String(encode);
    }
}
